package com.blb.bookms.controller;

import com.blb.bookms.config.SpringConfig;
import com.blb.bookms.entity.Book;
import com.blb.bookms.entity.Page;
import com.blb.bookms.service.IBookService;
import com.blb.bookms.service.impl.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 书籍控制器
 */
@WebServlet("/book.do")
public class BookServlet extends BaseServlet {

    @Autowired
    private IBookService bookService = SpringConfig.getBean(IBookService.class);

    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Book> allBooks = bookService.findAllBooks();
        req.setAttribute("books",allBooks);
        req.getRequestDispatcher("book.jsp").forward(req,resp);
    }

    public void findPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String curr = req.getParameter("current");
        String typeId = req.getParameter("typeId");
        int current = 1;
        if(curr != null){
            current = Integer.parseInt(curr);
        }
        int tId = 0;
        if(typeId != null){
            tId = Integer.parseInt(typeId);
        }
        Page<Book> page = bookService.findBooksPage(tId,current, Page.LIMIT);
        req.setAttribute("page",page);
        req.getRequestDispatcher("book.jsp").forward(req,resp);
    }

    public void saveBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("bookName");
        String price = req.getParameter("price");
        String typeId = req.getParameter("typeId");
        String author = req.getParameter("author");
        String publishTime = req.getParameter("publishTime");
        String publishOrg = req.getParameter("publishOrg");
        String state = req.getParameter("state");
        Book book = new Book();
        book.setBookName(name);
        book.setPrice(Float.parseFloat(price));
        book.setTypeId(Integer.parseInt(typeId));
        book.setAuthor(author);
        book.setPublishOrg(publishOrg);
        book.setPublishTime(publishTime);
        book.setState("1".equals(state) ? 1 : 0);
        bookService.saveBook(book);
        resp.sendRedirect("/index.jsp");
    }
}
